package com.huaxonline.boot.web.sign;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;

import java.util.function.Function;

/**
 * 签名算法枚举
 *
 * @author zhaoshulei
 * @since 2023/9/13
 */
public enum SignAlgorithm {

    /**
     * SHA256算法
     */
    SHA256(SignConstants.ALGORITHM_SHA256, SecureUtil::sha256),

    /**
     * MD5算法
     */
    MD5(SignConstants.ALGORITHM_MD5, SecureUtil::md5),

    /**
     * HMAC-SHA256算法
     */
    HMAC_SHA256(SignConstants.ALGORITHM_HMAC_SHA256, data -> {
        // HMAC-SHA256需要密钥，这里返回null，在具体实现中处理
        return null;
    });

    private final String name;
    private final Function<String, String> hashFunction;

    SignAlgorithm(String name, Function<String, String> hashFunction) {
        this.name = name;
        this.hashFunction = hashFunction;
    }

    public String getName() {
        return name;
    }

    public Function<String, String> getHashFunction() {
        return hashFunction;
    }

    /**
     * 根据名称获取算法
     */
    public static SignAlgorithm fromName(String name) {
        for (SignAlgorithm algorithm : values()) {
            if (algorithm.name.equals(name)) {
                return algorithm;
            }
        }
        return SHA256; // 默认返回SHA256
    }

    /**
     * 执行签名
     */
    public String sign(String data, String secret) {
        switch (this) {
            case HMAC_SHA256:
                return SecureUtil.hmac(HmacAlgorithm.HmacSHA256, secret).digestHex(data);
            default:
                return hashFunction.apply(data);
        }
    }
}